"""
@Project:ruiji
@File:index.py
@Author:马可
@Date:上午 09:38
"""
from email.mime import image
from flask import Blueprint,jsonify,request
from db import db
from utils.myredis import r
import json

index_blue = Blueprint('index',__name__)


# 获取商家信息
@index_blue.route("/getshops")
def getshops():
    code = '001'
    key = "shop"+code
    # r.removeall_str(key)   # 删除redis信息
    shop = r.get_str(key)
    if not shop:
        # 并发访问时允许一人访问
        res = r.setnx_str(key+'exit',key+'exit')
        # print('aaa')
        if res:
            # print('bbb')
            sql = "select * from shops where code='001'"
            shop = db.find(sql)
            r.set_str(key,json.dumps(shop))
    else:
        shop = json.loads(shop)
    return jsonify({
        'code':200,
        'shops':shop,
    })


# 获取所有分类
@index_blue.route('/getcates')
def getcates():
    cates = r.get_str('cates')
    if not cates:
        sql = "select id,name from category order by sort asc"
        res = db.find_all(sql)
        r.set_str('cates',json.dumps(res))
    else:
        res = json.loads(cates)
    data = []
    if res:
        data = [{
            'id':str(i['id']),
            'text':i['name'],
        } for i in res]
    return jsonify({
        'code':200,
        'catelist':data,
    })



#根据分类id获取此分类下的所有商品
@index_blue.route("/getGoodsBycateid")
def getGoodsBycateid():
    #获取分类id
    cateid = request.args.get('cateid')
    #获取缓存中此分类下的商品
    goods = r.get_str('goods'+cateid)
    #如果不存在查询
    if not goods:
        sql="select id,name,price,image,description from dish where category_id=%d and is_deleted=0"%(int(cateid))
        res = db.find_all(sql)
        data = []
        for i in res:
            dict = {'id':str(i['id']),'name':i['name'],'price':float(i['price']),'image':i[image],'description':i['description']}
            sql1 = "select value from dish_flavor where dish_id=%d"%(int(i['id']))
            flavors = db.find_all(sql1)
            flist = []
            for j in flavors:
                flist.append(j['value'])
            dict['flavors'] = flist
        data.append(dict)
        #把decimal转成float
        # data = [{'id':i['id'],'name':i['name'],'price':float(i['price']),'image':i['image'],'description':i['description']} for i in res]
        #加入缓存
        r.set_str('goods'+cateid,json.dumps(data))
    else:
        data = json.loads(goods)
    return jsonify({"code":200,'goodslist':data})



@index_blue.route('/addcart')
def addcart():
    # 获取数据
    userid = request.args.get('userid')
    gid = request.args.get('gid')
    count = request.args.get('count')
    type = request.args.get('type')
    flavors = request.args.get('flavors')

    if not all[userid,gid,count,type,flavors]:
        return jsonify({
            'code':10010,
            'msg':'数据不完整',
        })
    pkey = 'cart'+str(userid)+'goods'+str(gid)
    flag = r.is_exits(pkey)
    if int(flag) == 0:
        # 不存在
        r.hash_add(pkey,gid,count)
        r.hash_add(pkey,'type',type)
        r.hash_add(pkey,'flavors',json.dumps(flavors))
    else:
        # 如果存在更新
        r.hash_hincrby(pkey,gid,count)

    # 返回
    return jsonify({
        'code':200,
        'msg':'购买成功'
    })


@index_blue.route('/aaa')
def aaa():
    # 获取userid
    userid = request.args.get('userid')
    # 根据userid查询购物车信息
    carts = r.findall_str('cart'+str(userid))
    # 遍历购物车，查询每一个商品的属性
    clist = []
    for i in carts:
        dict={}
        goods = r.hash_getall(i.decode())
        for k,v in goods.items():
            kk = k.decode()
            vv = v.decode()
            if kk == "type":
                dict['type'] == vv
            elif kk == 'flavors':
                dict['flavors'] = json.loads(vv)
            else:
                dict['id'] = kk
                dict['count'] = vv
        clist.append(dict)
    if len(clist)>0:
        for i in clist:
            # 根据id和类型查询名称和价格
            if i['type'] == 1:
                sql = "select name,price from dish where id=%d"%(int(i['id']))
                res = db.find_all(sql)
    print(clist)
    return jsonify({
        'code':2,
        'msg':'成功',
        'data':res,

    })





